package com.doubao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.exception.BusinessException;
import com.doubao.common.result.Result;
import com.doubao.common.utils.RedisTemplateFactory;
import com.doubao.common.utils.SecurityUtil;
import com.doubao.user.constant.UserConstant;
import com.doubao.user.dto.VipInfoDTO;
import com.doubao.user.dto.request.UserInfoUpdateRequest;
import com.doubao.user.dto.request.UserPasswordUpdateRequest;
import com.doubao.user.dto.response.UserInfoResponse;
import com.doubao.user.entity.MembershipLevel;
import com.doubao.user.entity.User;
import com.doubao.user.entity.UserDailyToken;
import com.doubao.user.entity.UserMembership;
import com.doubao.user.mapper.MembershipLevelMapper;
import com.doubao.user.mapper.UserDailyTokenMapper;
import com.doubao.user.mapper.UserMapper;
import com.doubao.user.mapper.UserMembershipMapper;
import com.doubao.user.security.UserContext;
import com.doubao.user.service.MembershipService;
import com.doubao.user.service.TokenService;
import com.doubao.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类 - 具有Redis故障恢复能力的优化版
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final UserDailyTokenMapper userDailyTokenMapper;
    private final MembershipService membershipService;
    private final TokenService tokenService;
    private final UserMembershipMapper userMembershipMapper;
    private final MembershipLevelMapper membershipLevelMapper;

    @Override
    public User getUserById(Long userId) {
        if (userId == null) {
            return null;
        }

        // 使用优化版的RedisTemplateFactory执行Redis操作
        return RedisTemplateFactory.executeWithFallback(
                // Redis操作
                () -> {
                    RedisTemplate<String, Object> redisTemplate = RedisTemplateFactory.getRedisTemplate();
                    // 先查缓存
                    User user = (User) redisTemplate.opsForValue().get(UserConstant.USER_CACHE_PREFIX + userId);

                    if (user != null) {
                        log.debug("从Redis缓存获取用户信息成功, userId: {}", userId);
                        return user;
                    }

                    // 缓存未命中，从数据库查询
                    User dbUser = userMapper.selectUserById(userId);
                    if (dbUser != null) {
                        // 放入缓存
                        redisTemplate.opsForValue().set(UserConstant.USER_CACHE_PREFIX + userId, dbUser, 1, TimeUnit.HOURS);
                        log.debug("用户信息已更新到Redis缓存, userId: {}", userId);
                    }
                    return dbUser;
                },
                // 降级操作：直接从数据库查询
                () -> {
                    log.info("Redis不可用，直接从数据库查询用户信息, userId: {}", userId);
                    return userMapper.selectUserById(userId);
                }
        );
    }

    @Override
    public User getUserByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User getUserByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User getUserByEmail(String email) {
        if (StringUtils.isBlank(email)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public UserInfoResponse getCurrentUserInfo() {
        // 获取当前用户ID
        Long userId = UserContext.getUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }

        // 使用优化后的getUserById方法
        User user = getUserById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        UserInfoResponse response = new UserInfoResponse();
        BeanUtils.copyProperties(user, response);

        // 判断是否绑定了微信 - 使用user表中的字段
        boolean isWechatBound = StringUtils.isNotBlank(user.getUnionid())
                || StringUtils.isNotBlank(user.getMiniappOpenid())
                || StringUtils.isNotBlank(user.getOfficialOpenid())
                || StringUtils.isNotBlank(user.getWebOpenid())
                || StringUtils.isNotBlank(user.getAppOpenid());

        response.setWechatBound(isWechatBound);

        return response;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateUserInfo(UserInfoUpdateRequest request) {
        // 获取当前登录用户ID
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 校验手机号是否被占用
        if (StringUtils.isNotBlank(request.getPhone())
                && !request.getPhone().equals(user.getPhone())
                && isPhoneExists(request.getPhone())) {
            return Result.failed("手机号已被使用");
        }

        // 校验邮箱是否被占用
        if (StringUtils.isNotBlank(request.getEmail())
                && !request.getEmail().equals(user.getEmail())
                && isEmailExists(request.getEmail())) {
            return Result.failed("邮箱已被使用");
        }

        // 更新信息
        boolean needUpdate = false;
        if (StringUtils.isNotBlank(request.getNickname()) && !request.getNickname().equals(user.getNickname())) {
            user.setNickname(request.getNickname());
            needUpdate = true;
        }
        if (StringUtils.isNotBlank(request.getAvatar()) && !request.getAvatar().equals(user.getAvatar())) {
            user.setAvatar(request.getAvatar());
            needUpdate = true;
        }
        if (StringUtils.isNotBlank(request.getPhone()) && !request.getPhone().equals(user.getPhone())) {
            user.setPhone(request.getPhone());
            needUpdate = true;
        }
        if (StringUtils.isNotBlank(request.getEmail()) && !request.getEmail().equals(user.getEmail())) {
            user.setEmail(request.getEmail());
            needUpdate = true;
        }

        if (needUpdate) {
            user.setUpdatedAt(LocalDateTime.now());
            int result = userMapper.updateById(user);

            if (result > 0) {
                // 删除缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                            return null;
                        },
                        () -> null
                );
            }
        }

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updatePassword(UserPasswordUpdateRequest request) {
        // 获取当前登录用户ID
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 校验旧密码
        if (!SecurityUtil.matchPassword(request.getOldPassword(), user.getPassword())) {
            return Result.failed("旧密码错误");
        }

        // 校验新密码与确认密码是否一致
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            return Result.failed("两次输入的新密码不一致");
        }

        // 更新密码
        user.setPassword(SecurityUtil.encryptPassword(request.getNewPassword()));
        user.setUpdatedAt(LocalDateTime.now());
        int result = userMapper.updateById(user);

        if (result > 0) {
            // 删除缓存
            RedisTemplateFactory.executeWithFallback(
                    () -> {
                        RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                        return null;
                    },
                    () -> null
            );
        }

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateVipStatus(Long userId, Integer vipStatus) {
        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        if (!Objects.equals(user.getVipStatus(), vipStatus)) {
            user.setVipStatus(vipStatus);
            user.setUpdatedAt(LocalDateTime.now());
            int result = userMapper.updateById(user);

            if (result > 0) {
                // 更新缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().opsForValue().set(
                                    UserConstant.USER_CACHE_PREFIX + userId, user, 1, TimeUnit.HOURS);
                            return null;
                        },
                        () -> null
                );
            }
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateDailyTokensLimit(Long userId, Integer tokenBalance) {
        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        if (!Objects.equals(user.getTotalTokensBalance(), tokenBalance)) {
            user.setTotalTokensBalance(tokenBalance);
            user.setUpdatedAt(LocalDateTime.now());
            int result = userMapper.updateById(user);

            if (result > 0) {
                // 更新缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().opsForValue().set(
                                    UserConstant.USER_CACHE_PREFIX + userId, user, 1, TimeUnit.HOURS);
                            return null;
                        },
                        () -> null
                );

                // 同时更新今日Token记录表中的限额
                LocalDate today = LocalDate.now();
                String dateStr = today.toString();
                LambdaQueryWrapper<UserDailyToken> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserDailyToken::getUserId, userId)
                        .eq(UserDailyToken::getDate, today);
                UserDailyToken dailyToken = userDailyTokenMapper.selectOne(wrapper);
                if (dailyToken != null) {
                    userDailyTokenMapper.updateTokenLimit(userId, dateStr, tokenBalance);
                }
            }
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> increaseTokensUsed(Long userId, Long tokens) {
        if (userId == null || tokens == null || tokens <= 0) {
            return Result.failed("参数错误");
        }
        try {
            int result = userMapper.increaseTokensUsed(userId, tokens);
            if (result > 0) {
                // 清除缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                            return null;
                        },
                        () -> null
                );
            }
            return Result.success();
        } catch (Exception e) {
            log.error("增加用户token使用量失败", e);
            return Result.failed("增加token使用量失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateLastLogin(Long userId, String ip) {
        if (userId == null) {
            return Result.failed("用户ID不能为空");
        }
        try {
            int result = userMapper.updateLastLogin(userId, ip);
            if (result > 0) {
                // 清除缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                            return null;
                        },
                        () -> null
                );
            }
            return Result.success();
        } catch (Exception e) {
            log.error("更新用户最后登录信息失败", e);
            return Result.failed("更新最后登录信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> disableUser(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        user.setStatus(UserConstant.STATUS_DISABLED);
        user.setUpdatedAt(LocalDateTime.now());
        int result = userMapper.updateById(user);

        if (result > 0) {
            // 更新缓存
            RedisTemplateFactory.executeWithFallback(
                    () -> {
                        RedisTemplateFactory.getRedisTemplate().opsForValue().set(
                                UserConstant.USER_CACHE_PREFIX + userId, user, 1, TimeUnit.HOURS);
                        return null;
                    },
                    () -> null
            );
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> enableUser(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        user.setStatus(UserConstant.STATUS_NORMAL);
        user.setUpdatedAt(LocalDateTime.now());
        int result = userMapper.updateById(user);

        if (result > 0) {
            // 更新缓存
            RedisTemplateFactory.executeWithFallback(
                    () -> {
                        RedisTemplateFactory.getRedisTemplate().opsForValue().set(
                                UserConstant.USER_CACHE_PREFIX + userId, user, 1, TimeUnit.HOURS);
                        return null;
                    },
                    () -> null
            );
        }
        return Result.success();
    }

    @Override
    public boolean isTokenLimitExceeded(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return true;
        }

        // 查询今日使用量
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<UserDailyToken> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDailyToken::getUserId, userId)
                .eq(UserDailyToken::getDate, today);
        UserDailyToken dailyToken = userDailyTokenMapper.selectOne(wrapper);

        if (dailyToken == null) {
            // 今日未使用，未超限
            return false;
        }

        // 计算总使用量
        int totalUsed = dailyToken.getPromptTokens() + dailyToken.getCompletionTokens();
        return totalUsed >= user.getTotalTokensBalance();
    }

    @Override
    public int getAvailableTokens(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return 0;
        }

        // 查询今日使用量
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<UserDailyToken> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDailyToken::getUserId, userId)
                .eq(UserDailyToken::getDate, today);
        UserDailyToken dailyToken = userDailyTokenMapper.selectOne(wrapper);

        if (dailyToken == null) {
            // 今日未使用
            return user.getTotalTokensBalance();
        }

        // 计算总使用量
        int totalUsed = dailyToken.getPromptTokens() + dailyToken.getCompletionTokens();
        int available = user.getTotalTokensBalance() - totalUsed;
        return Math.max(0, available);
    }

    @Override
    public boolean isUsernameExists(String username) {
        if (StringUtils.isBlank(username)) {
            return false;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectCount(wrapper) > 0;
    }

    @Override
    public boolean isPhoneExists(String phone) {
        if (StringUtils.isBlank(phone)) {
            return false;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectCount(wrapper) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        if (StringUtils.isBlank(email)) {
            return false;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email)
                .eq(User::getDeleted, UserConstant.NOT_DELETED);
        return userMapper.selectCount(wrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindWechat(Long userId, String openid, String unionid, String type) {
        log.info("开始绑定微信账号: userId={}, openid={}, unionid={}, type={}", userId, openid, unionid, type);
        
        if (userId == null) {
            log.error("绑定微信账号失败: 用户ID为空");
            return false;
        }
        
        User user = getUserById(userId);
        if (user == null) {
            log.error("绑定微信账号失败: 用户不存在, userId={}", userId);
            return false;
        }
        
        // 根据绑定类型设置不同的OpenID字段
        boolean updated = false;
        if ("miniapp".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(openid) && !openid.equals(user.getMiniappOpenid())) {
                user.setMiniappOpenid(openid);
                updated = true;
            }
        } else if ("mp".equalsIgnoreCase(type) || "official".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(openid) && !openid.equals(user.getOfficialOpenid())) {
                user.setOfficialOpenid(openid);
                updated = true;
            }
        } else if ("web".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(openid) && !openid.equals(user.getWebOpenid())) {
                user.setWebOpenid(openid);
                updated = true;
            }
        } else if ("app".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(openid) && !openid.equals(user.getAppOpenid())) {
                user.setAppOpenid(openid);
                updated = true;
            }
        }
        
        // 设置统一的UnionID
        if (StringUtils.isNotBlank(unionid) && !unionid.equals(user.getUnionid())) {
            user.setUnionid(unionid);
            updated = true;
        }
        
        if (updated) {
            user.setUpdatedAt(LocalDateTime.now());
            int result = userMapper.updateById(user);
            
            if (result > 0) {
                // 删除缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                            return null;
                        },
                        () -> null
                );
                log.info("绑定微信账号成功: userId={}, type={}", userId, type);
                return true;
            }
        } else {
            log.info("无需更新微信绑定信息: userId={}, type={}", userId, type);
            return true; // 没有变化也视为成功
        }
        
        log.error("绑定微信账号失败: 数据库更新失败, userId={}, type={}", userId, type);
        return false;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unbindWechat(Long userId, String type) {
        log.info("开始解绑微信账号: userId={}, type={}", userId, type);
        
        if (userId == null) {
            log.error("解绑微信账号失败: 用户ID为空");
            return false;
        }
        
        User user = getUserById(userId);
        if (user == null) {
            log.error("解绑微信账号失败: 用户不存在, userId={}", userId);
            return false;
        }
        
        // 根据解绑类型清除不同的OpenID字段
        boolean updated = false;
        if ("miniapp".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(user.getMiniappOpenid())) {
                user.setMiniappOpenid(null);
                updated = true;
            }
        } else if ("mp".equalsIgnoreCase(type) || "official".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(user.getOfficialOpenid())) {
                user.setOfficialOpenid(null);
                updated = true;
            }
        } else if ("web".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(user.getWebOpenid())) {
                user.setWebOpenid(null);
                updated = true;
            }
        } else if ("app".equalsIgnoreCase(type)) {
            if (StringUtils.isNotBlank(user.getAppOpenid())) {
                user.setAppOpenid(null);
                updated = true;
            }
        } else if ("all".equalsIgnoreCase(type)) {
            // 解绑所有
            user.setMiniappOpenid(null);
            user.setOfficialOpenid(null);
            user.setWebOpenid(null);
            user.setAppOpenid(null);
            user.setUnionid(null);
            updated = true;
        }
        
        if (updated) {
            user.setUpdatedAt(LocalDateTime.now());
            int result = userMapper.updateById(user);
            
            if (result > 0) {
                // 删除缓存
                RedisTemplateFactory.executeWithFallback(
                        () -> {
                            RedisTemplateFactory.getRedisTemplate().delete(UserConstant.USER_CACHE_PREFIX + userId);
                            return null;
                        },
                        () -> null
                );
                log.info("解绑微信账号成功: userId={}, type={}", userId, type);
                return true;
            }
        } else {
            log.info("无需解绑微信账号: userId={}, type={}", userId, type);
            return true; // 没有变化也视为成功
        }
        
        log.error("解绑微信账号失败: 数据库更新失败, userId={}, type={}", userId, type);
        return false;
    }
    
    @Override
    public boolean isWechatBound(Long userId) {
        if (userId == null) {
            return false;
        }
        
        User user = getUserById(userId);
        if (user == null) {
            return false;
        }
        
        return StringUtils.isNotBlank(user.getUnionid())
                || StringUtils.isNotBlank(user.getMiniappOpenid())
                || StringUtils.isNotBlank(user.getOfficialOpenid())
                || StringUtils.isNotBlank(user.getWebOpenid())
                || StringUtils.isNotBlank(user.getAppOpenid());
    }

    @Override
    public VipInfoDTO getUserVipInfo(Long userId) {
        log.info("开始获取用户VIP信息: userId={}", userId);

        if (userId == null) {
            log.error("用户ID为空");
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 1. 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.error("用户不存在: userId={}", userId);
            throw new RuntimeException("用户不存在");
        }

        // 2. 初始化DTO
        VipInfoDTO vipInfo = new VipInfoDTO();
        vipInfo.setUserId(userId);

        // 3. 获取用户当前有效的会员信息
        UserMembership membership = getCurrentValidMembership(userId);

        if (membership == null) {
            log.info("用户没有有效的会员: userId={}", userId);
            // 非VIP用户返回基础信息
            vipInfo.setIsVip(false);
            vipInfo.setStatus(0);
            return vipInfo;
        }

        // 4. 获取会员等级信息
        MembershipLevel level = membershipLevelMapper.selectById(membership.getLevelId());
        if (level == null) {
            log.error("会员等级不存在: levelId={}", membership.getLevelId());
            throw new RuntimeException("会员等级配置错误");
        }

        // 5. 填充VIP信息
        vipInfo.setIsVip(true);
        vipInfo.setLevelId(level.getId());
        vipInfo.setLevelName(level.getName());
        vipInfo.setLevelCode(level.getCode());
        vipInfo.setSubscriptionType(membership.getSubscriptionType());
        vipInfo.setSubscriptionTypeText(getSubscriptionTypeText(membership.getSubscriptionType()));
        vipInfo.setStartTime(membership.getStartTime());
        vipInfo.setExpireTime(membership.getExpireTime());
        vipInfo.setStatus(membership.getStatus());
        vipInfo.setSource(membership.getSource());

        // 计算剩余天数
        LocalDateTime now = LocalDateTime.now();
        long remainingDays = ChronoUnit.DAYS.between(now, membership.getExpireTime());
        vipInfo.setRemainingDays(remainingDays > 0 ? remainingDays : 0);

        // 会员权益信息
        vipInfo.setDailyTokenLimit(level.getDailyTokenLimit());
        vipInfo.setChatLimit(level.getChatLimit());
        vipInfo.setSwitchAgentLimit(level.getSwitchAgentLimit());
        vipInfo.setRemainingChatCount(membership.getRemainingChatCount());
        vipInfo.setRemainingSwitchCount(membership.getRemainingSwitchCount());

        log.info("获取用户VIP信息成功: userId={}, levelName={}, subscriptionType={}, expireTime={}",
                userId, level.getName(), membership.getSubscriptionType(), membership.getExpireTime());

        return vipInfo;
    }

    /**
     * 获取用户当前有效的会员信息
     *
     * @param userId 用户ID
     * @return 会员信息，如果没有则返回null
     */
    private UserMembership getCurrentValidMembership(Long userId) {
        log.debug("查询用户当前有效会员: userId={}", userId);

        LambdaQueryWrapper<UserMembership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMembership::getUserId, userId)
                .eq(UserMembership::getStatus, 1)  // 状态为有效
                .ge(UserMembership::getExpireTime, LocalDateTime.now())  // 未过期
                .orderByDesc(UserMembership::getExpireTime)  // 按到期时间倒序
                .last("LIMIT 1");  // 只取最新的一条

        UserMembership membership = userMembershipMapper.selectOne(wrapper);

        if (membership != null) {
            log.debug("找到有效会员: membershipId={}, levelId={}, expireTime={}",
                    membership.getId(), membership.getLevelId(), membership.getExpireTime());
        } else {
            log.debug("未找到有效会员: userId={}", userId);
        }

        return membership;
    }

    /**
     * 获取订阅类型的中文文本
     *
     * @param subscriptionType 订阅类型
     * @return 中文文本
     */
    private String getSubscriptionTypeText(String subscriptionType) {
        if (subscriptionType == null) {
            return "未知类型";
        }

        switch (subscriptionType) {
            case "WEEKLY":
                return "周卡";
            case "MONTHLY":
                return "月卡";
            case "QUARTERLY":
                return "季卡";
            case "YEARLY":
                return "年卡";
            case "TEMP":
                return "临时卡";
            case "SINGLE":
                return "单次卡";
            default:
                log.warn("未知的订阅类型: {}", subscriptionType);
                return subscriptionType;
        }
    }
}